package com.spring.sunflower.main.fragment

import android.content.Intent
import android.os.Handler
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.OrientationHelper
import androidx.recyclerview.widget.RecyclerView
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import com.spring.sunflower.R
import com.spring.sunflower.anchor.PersonalDetailActivity
import com.spring.sunflower.base.BaseFragment
import com.spring.sunflower.bean.*
import com.spring.sunflower.constant.Constant
import com.spring.sunflower.conversation.ChatVideoActivity
import com.spring.sunflower.dialog.BottomCommentDialog
import com.spring.sunflower.dialog.OnPermissionIntroClickListener
import com.spring.sunflower.event.FollowEvent
import com.spring.sunflower.main.MainContract
import com.spring.sunflower.main.adapter.TikTokAdapter
import com.spring.sunflower.main.adapter.TikTokShowAdapter
import com.spring.sunflower.main.presenter.VideoShowPresenter
import com.spring.sunflower.util.StatusBarUtil
import com.spring.sunflower.util.Utils
import com.spring.sunflower.util.cache.PreloadManager
import com.spring.sunflower.video.OnViewPagerListener
import com.spring.sunflower.video.ViewPagerLayoutManager
import com.spring.sunflower.widget.EndlessRecyclerOnScrollListener
import com.spring.sunflower.widget.TikTokController
import org.greenrobot.eventbus.Subscribe
import xyz.doikki.videoplayer.exo.ExoMediaPlayer
import xyz.doikki.videoplayer.player.VideoView
import xyz.doikki.videoplayer.util.L

/**
 * Created by Kevin on 2021/6/25<br></br>
 *
 *
 * Describe:<br></br>
 */
class VideoShowFragment : BaseFragment<VideoShowPresenter>(), MainContract.VideoShowView,
    OnRefreshListener, OnLoadMoreListener, OnViewPagerListener,
    TikTokShowAdapter.OnVideoShowActionListener {
    private var rvRecyclerView: RecyclerView? = null
    private var mAdapter: TikTokShowAdapter? = null
    private var mData: MutableList<VideoPlayBean.DatasBean> = ArrayList()
    private var pageIndex = 1
    private var refreshLayout: SmartRefreshLayout? = null
    private var mVideoView: VideoView<ExoMediaPlayer>? = null
    private var mController: TikTokController? = null
    private var mCurPos = 0
    private var mUserID = ""
    private var mCommentDialog: BottomCommentDialog? = null
    private var toolbar: Toolbar? = null
    private var commentPageIndex = 1
    override fun setLayoutResId(): Int = R.layout.fragment_video_show

    override fun initView() {
//        toolbar = mView.findViewById(R.id.toolBar)
//        StatusBarUtil.setHeightAndPadding(mActivity, toolbar)
        refreshLayout = mView.findViewById(R.id.refreshLayout)
        rvRecyclerView = mView.findViewById(R.id.rvRecyclerView)
        mUserID = getField(Constant.KEY_USERID, "")
        mAdapter = TikTokShowAdapter(mActivity, mData)
        val layoutManager = ViewPagerLayoutManager(mActivity, OrientationHelper.VERTICAL)
        rvRecyclerView!!.layoutManager = layoutManager

//        val pagerSnapHelper = PagerSnapHelper()
//        pagerSnapHelper.attachToRecyclerView(rvRecyclerView!!)
        rvRecyclerView!!.adapter = mAdapter
        mAdapter?.setOnVideoShowActionListener(this)
        layoutManager.setOnViewPagerListener(this)
        val endlessScrollListener = object : EndlessRecyclerOnScrollListener(layoutManager) {
            override fun onLoadMore(current_page: Int) {
                mPresenter.getVideoList(
                    (++pageIndex).toString()
                )
            }
        }
        rvRecyclerView!!.addOnScrollListener(endlessScrollListener)
        refreshLayout!!.setEnableLoadMore(false)
        refreshLayout!!.setOnLoadMoreListener(this)
        refreshLayout!!.setOnRefreshListener(this)

        mPresenter.getVideoList(pageIndex.toString())
        mVideoView = VideoView<ExoMediaPlayer>(mActivity!!)
        mController = TikTokController(mActivity!!)
        mVideoView?.let {
            it.setScreenScaleType(VideoView.SCREEN_SCALE_CENTER_CROP)
            it.setLooping(true)
            it.setVideoController(mController!!)
        }
    }

    override fun initData() {
    }

    override fun initListener() {
    }

    override fun loadData() {
//        mPresenter.getVideoList(pageIndex.toString())
    }

    override fun setPresenter(): VideoShowPresenter = VideoShowPresenter((this))

    override fun showVideoList(data: MutableList<VideoPlayBean.DatasBean>?) {
        if (pageIndex == 1) {
            mCurPos = 0
            mAdapter!!.refreshData(data)
        } else {
            mAdapter!!.addData(data)
        }
        refreshLayout?.let {
            if (it.isRefreshing) {
                it.finishRefresh()
                Handler().postDelayed(object : Runnable {
                    override fun run() {
                        startPlay(mCurPos)
                    }

                }, 1000)
            }
            if (it.isLoading) {
                it.finishLoadMore()
            }
        }
    }

    override fun showVideoLikeSuccess() {
        val itemView: View = rvRecyclerView!!.getChildAt(0)
        val viewHolder: TikTokShowAdapter.VideoHolder =
            itemView.tag as TikTokShowAdapter.VideoHolder
        val datasBean = mData[mCurPos]
        if ("1" == datasBean.isLike) {
            datasBean.isLike = "0"
            mData[mCurPos] = datasBean
            val i = viewHolder.tvLike.text.toString().toInt()
            viewHolder.tvLike.text = (i - 1).toString()
            viewHolder.ivFollowed.setImageResource(R.drawable.icon_video_unstar)
        } else {
            datasBean.isLike = "1"
            mData[mCurPos] = datasBean
            val i = viewHolder.tvLike.text.toString().toInt()
            viewHolder.tvLike.text = (i + 1).toString()
            viewHolder.ivFollowed.setImageResource(R.drawable.icon_video_star)
        }


    }

    override fun setFollowedSuccess() {
        val datasBean = mData[mCurPos]
        datasBean.isFavorite = "1"
        mData[mCurPos] = datasBean
        val itemView: View = rvRecyclerView!!.getChildAt(0)
        val viewHolder: TikTokShowAdapter.VideoHolder =
            itemView.tag as TikTokShowAdapter.VideoHolder
        viewHolder.ivAddFavorite.visibility = View.GONE
    }

    override fun setFollowedFailed() {
    }

    override fun liveApplySuccess() {
        val datasBean = mData[mCurPos]
        val intent = Intent(mActivity, ChatVideoActivity::class.java)
        intent.putExtra(Constant.VIDEO_CALL_SELF_DIAL, true)
        intent.putExtra(Constant.VIDEO_CALL_OTHER_ID, datasBean.memberId)
        intent.putExtra(Constant.VIDEO_CALL_OTHER_FACE_URL, datasBean.photo)
        intent.putExtra(Constant.VIDEO_CALL_OTHER_NICKNAME, datasBean.nickname)
        startActivity(intent)
    }

    override fun sayHelloSuccess() {
        showToast("搭讪成功")
    }

    override fun releaseCommentSuccess(data: VideoCommentReleaseBean.DatasBean?) {
        mCommentDialog?.addComment(data!!)
    }

    override fun releaseSubCommentSuccess(data: VideoSubCommentReleaseBean.DatasBean?) {
        mCommentDialog?.addSubComment(data!!)
    }

    override fun showComment(data: MutableList<VideoCommentBean.DatasBean>?) {
        mCommentDialog?.updateComment(data!!)
//        if (pageIndex==1){
//        }else{
//
//        }
    }

    override fun showSubComment(data: MutableList<VideoSubCommentBean.DatasBean>?) {
    }

    override fun showCommentLikeSuccess(isChild: Boolean) {
        mCommentDialog?.refreshCommentFav(isChild)
    }


    override fun onRefresh(refreshLayout: RefreshLayout) {
        pageIndex = 1
        mPresenter.getVideoList(pageIndex.toString())
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mPresenter.getVideoList((++pageIndex).toString())
    }

    override fun onInitComplete() {

        //自动播放第index条
        if (isUIVisible) {
            startPlay(0)
        }
    }

    override fun onPageRelease(isNext: Boolean, position: Int) {
        if (mCurPos == position) {
            mVideoView!!.release()
        }
    }

    override fun onPageSelected(position: Int, isBottom: Boolean) {
        if (mCurPos == position) return
        startPlay(position)
    }

    private fun startPlay(position: Int) {
        if (rvRecyclerView == null) return
        val itemView: View = rvRecyclerView!!.getChildAt(0) ?: return
        val viewHolder: TikTokShowAdapter.VideoHolder =
            itemView.tag as TikTokShowAdapter.VideoHolder
        mVideoView?.release()
        Utils.removeViewFormParent(mVideoView)
        val item = mData.get(position)
        val playUrl: String =
            PreloadManager.getInstance(mActivity).getPlayUrl(item.videoPath)
        L.i("startPlay: position: $position  url: $playUrl")
        mVideoView?.setUrl(playUrl)
        //请点进去看isDissociate的解释
        mController?.addControlComponent(viewHolder.mTikTokView, true)
        viewHolder.mPlayerContainer.addView(mVideoView, 0)
        viewHolder.loadingView.visibility = View.INVISIBLE
        mVideoView?.start()
//        mVideoView!!.loadView.visibility = View.GONE
        mCurPos = position
    }

    override fun onPause() {
        super.onPause()
        mVideoView!!.pause()
    }

    override fun onResume() {
        super.onResume()
        if (isUIVisible) {
//            mVideoView?.resume()
            startPlay(mCurPos)
        }
        printD("isViewCreated=${isViewCreated},isUIVisible=${isUIVisible}")
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            mVideoView?.isMute = false
            startPlay(mCurPos)
        } else {
            val currentPlayState = mVideoView?.currentPlayState
            if (currentPlayState == 1) {
                mVideoView?.isMute = true
            } else {
                mVideoView?.pause()
            }


        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mVideoView!!.release()
    }

    override fun onFollowed(position: Int) {
        val datasBean = mData[position]
        val favorite = datasBean.isFavorite
        if ("1" == favorite) {//已关注
            mPresenter.setFollowed(datasBean.memberId, "0")
        } else {
            mPresenter.setFollowed(datasBean.memberId, "1")
        }
    }

    override fun onLike(position: Int) {
        val datasBean = mData[position]
        if ("1" == datasBean.isLike) {
            mPresenter.getVideoShowLike("0", datasBean.id)
        } else {
            mPresenter.getVideoShowLike("1", datasBean.id)
        }
    }

    override fun onComment(position: Int) {
        mCommentDialog = BottomCommentDialog(mActivity)
        mCommentDialog?.setOnReleaseCommentListener(object :
            BottomCommentDialog.OnReleaseCommentListener {
            override fun onReleaseComment(comment: String) {
                mPresenter.releaseComment(comment, mData[mCurPos].id)
            }

            override fun onSubReleaseComment(comment: String, parentCommentId: String) {
                mPresenter.releaseSubComment(comment, parentCommentId)
            }

            override fun onParentCommentFav(groupPosition: Int, commentId: String) {
                mPresenter.getVideoCommentLike("1", commentId, false)
            }

            override fun onChildCommentFav(
                groupPosition: Int,
                childPosition: Int,
                commentId: String
            ) {
                mPresenter.getVideoCommentLike("1", commentId, true)
            }

            override fun onCommentLoadmore() {
                mPresenter.getComment((++pageIndex).toString(), mData[mCurPos].id)
            }

        })
        XPopup.Builder(mActivity)
            .moveUpToKeyboard(false)
            .enableDrag(true)
            .hasShadowBg(false)
            .setPopupCallback(object : SimpleCallback() {
                override fun onShow(popupView: BasePopupView?) {
                    super.onShow(popupView)
                    mPresenter.getComment("1", mData[mCurPos].id)
                }

                override fun onDismiss(popupView: BasePopupView?) {
                    super.onDismiss(popupView)
                    commentPageIndex = 1
                }
            })
            .asCustom(mCommentDialog)
            .show()
    }

    override fun onAvatarClick(position: Int) {
        val datasBean = mData[position]
        val intent = Intent(activity, PersonalDetailActivity::class.java)
        intent.putExtra(Constant.KEY_TARGET_ID, datasBean.getMemberId().toString())
        startActivity(intent)
    }

    override fun onChatClick(position: Int) {
        val datasBean = mData[position]
        if ("4".equals(datasBean.status)) {
//            mPresenter.applyChat(mUserID, datasBean.memberId,datasBean.photo,datasBean.nickname)
            startVideoCall(mUserID, datasBean.memberId, datasBean.photo, datasBean.nickname)
        } else {
            mPresenter.sayHello(datasBean.memberId,mUserID)
        }

    }

    private fun startVideoCall(
        userID: String,
        anchorID: String,
        mOtherFaceUrl: String,
        mOtherShowName: String
    ) {
        if (!XXPermissions.isGranted(mActivity, Permission.CAMERA) || !XXPermissions.isGranted(
                mActivity,
                Permission.RECORD_AUDIO
            )
        ) {
            showPermissionIntroDialog(
                arrayOf(
                    getString(R.string.permission_audio_title),
                    getString(R.string.permission_camera_title)
                ),
                arrayOf(
                    getString(R.string.permission_audio_desc),
                    getString(R.string.permission_camera_desc)
                ),
                object : OnPermissionIntroClickListener {
                    override fun onClickOK() {
                        XXPermissions.with(mActivity)
                            .permission(Permission.RECORD_AUDIO, Permission.CAMERA)
                            .request(object : OnPermissionCallback {
                                override fun onGranted(
                                    permissions: List<String>,
                                    all: Boolean
                                ) {
                                    if (all) {
                                        saveField(Constant.KEY_USERID_CHATTER, anchorID)
                                        saveField(
                                            Constant.KEY_AVATAR_CHATTER,
                                            mOtherFaceUrl
                                        )
                                        saveField(
                                            Constant.KEY_NICKNAME_CHATTER,
                                            mOtherShowName
                                        )
                                        mPresenter.applyChat(
                                            userID,
                                            anchorID
                                        )
                                        mGrantedCameraPermission = true
                                        mGratedRecordPermission = true
                                    } else {
                                        showPermissionIntroDialog(
                                            getString(R.string.permission_denied_title),
                                            "无法正常进行视频通话",
                                            null
                                        )
                                    }
                                }

                                override fun onDenied(
                                    permissions: List<String>,
                                    never: Boolean
                                ) {
                                    showPermissionIntroDialog(
                                        getString(R.string.permission_denied_title),
                                        "无法正常进行视频通话",
                                        null
                                    )
                                }
                            })
                    }

                    override fun onClickCancel() {}
                })
        } else {
            saveField(Constant.KEY_USERID_CHATTER, anchorID)
            saveField(
                Constant.KEY_AVATAR_CHATTER,
                mOtherFaceUrl
            )
            saveField(
                Constant.KEY_NICKNAME_CHATTER,
                mOtherShowName
            )
            mPresenter.applyChat(userID, anchorID)
        }
    }

    override fun shouldRegisterEventBus(): Boolean {
        return true
    }

    @Subscribe
    fun subscribeFollow(event: FollowEvent) {
        val datasBean = mData[mCurPos]
        val memberId = datasBean.memberId
        if (event.userID == memberId) {
            if (event.isHasFollowed) {
                datasBean.isFavorite = "1"
                mData[mCurPos] = datasBean
                val itemView: View = rvRecyclerView!!.getChildAt(0)
                val viewHolder: TikTokShowAdapter.VideoHolder =
                    itemView.tag as TikTokShowAdapter.VideoHolder
                viewHolder.ivAddFavorite.visibility = View.GONE
            } else {
                datasBean.isFavorite = "0"
                mData[mCurPos] = datasBean
                val itemView: View = rvRecyclerView!!.getChildAt(0)
                val viewHolder: TikTokShowAdapter.VideoHolder =
                    itemView.tag as TikTokShowAdapter.VideoHolder
                viewHolder.ivAddFavorite.visibility = View.VISIBLE
            }
        }

    }
}